const User = require('../models/User');
const path = require('path');
const fs = require('fs').promises;
const db = require('../config/database');
const { logger } = require('../utils/logger');

/**
 * 用户管理控制器
 * 处理用户信息管理相关功能
 */
class UserController {
  /**
   * 获取用户信息
   * GET /api/users/:userId
   */
  static async getUserById(req, res) {
    try {
      const { userId } = req.params;
      
      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      res.json({
        success: true,
        message: '获取用户信息成功',
        data: {
          user: user.toSafeObject()
        }
      });
    } catch (error) {
      logger.error('获取用户信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户信息失败',
        error_code: 'GET_USER_ERROR'
      });
    }
  }

  /**
   * 获取所有用户统计信息 (管理员)
   * GET /api/admin/users/statistics
   */
  static async getAllUserStats(req, res) {
    try {
      const [stats] = await db.execute(`
        SELECT
          COUNT(*) AS totalUsers,
          SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) AS activeUsers,
          SUM(CASE WHEN membership_level = 'VIP' THEN 1 ELSE 0 END) AS vipUsers,
          (SELECT SUM(total_amount) FROM orders WHERE status = 'completed') AS totalRevenue
        FROM users
      `);

      res.json({
        success: true,
        data: {
          totalUsers: stats[0].totalUsers || 0,
          activeUsers: stats[0].activeUsers || 0,
          vipUsers: stats[0].vipUsers || 0,
          totalRevenue: parseFloat(stats[0].totalRevenue || 0),
        }
      });
    } catch (error) {
      logger.error('获取所有用户统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户统计数据失败',
        error_code: 'GET_ALL_USER_STATS_ERROR'
      });
    }
  }

  /**
   * 更新用户信息
   * PUT /api/users/:userId
   */
  static async updateUser(req, res) {
    try {
      const { userId } = req.params;
      const updateData = req.body;
      
      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      // 更新用户信息
      const updatedUser = await user.update(updateData);

      res.json({
        success: true,
        message: '用户信息更新成功',
        data: {
          user: updatedUser.toSafeObject()
        }
      });
    } catch (error) {
      logger.error('更新用户信息失败:', error);
      res.status(500).json({
        success: false,
        message: '更新用户信息失败',
        error_code: 'UPDATE_USER_ERROR'
      });
    }
  }

  /**
   * 上传用户头像
   * POST /api/users/:userId/avatar
   */
  static async uploadAvatar(req, res) {
    try {
      const { userId } = req.params;
      
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '请选择要上传的头像文件',
          error_code: 'NO_FILE'
        });
      }

      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      // 生成文件名
      const fileExtension = path.extname(req.file.originalname);
      const fileName = `avatar_${userId}_${Date.now()}${fileExtension}`;
      const filePath = path.join(process.env.UPLOAD_PATH || 'uploads', 'avatars', fileName);
      
      // 确保目录存在
      const avatarDir = path.dirname(filePath);
      await fs.mkdir(avatarDir, { recursive: true });
      
      // 保存文件
      await fs.writeFile(filePath, req.file.buffer);
      
      // 删除旧头像文件（如果存在）
      if (user.profile_image_url) {
        try {
          const oldFilePath = path.join(process.cwd(), user.profile_image_url);
          await fs.unlink(oldFilePath);
        } catch (error) {
          logger.warn('删除旧头像文件失败:', error.message);
        }
      }
      
      // 更新用户头像URL
      const avatarUrl = `/uploads/avatars/${fileName}`;
      await user.update({ profile_image_url: avatarUrl });
      
      res.json({
        success: true,
        message: '头像上传成功',
        data: {
          avatar_url: avatarUrl
        }
      });
    } catch (error) {
      logger.error('头像上传失败:', error);
      res.status(500).json({
        success: false,
        message: '头像上传失败',
        error_code: 'AVATAR_UPLOAD_ERROR'
      });
    }
  }

  /**
   * 获取用户积分历史
   * GET /api/users/:userId/points-history
   */
  static async getPointsHistory(req, res) {
    try {
      const { userId } = req.params;
      const { page = 1, limit = 20 } = req.query;
      
      const offset = (page - 1) * limit;
      
      // 这里假设有积分历史表，实际需要根据数据库设计调整
      const sql = `
        SELECT 
          points_change,
          reason,
          created_at,
          order_id
        FROM points_history 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
      `;
      
      const countSql = 'SELECT COUNT(*) as total FROM points_history WHERE user_id = ?';
      
      const [historyRows] = await db.execute(sql, [userId, parseInt(limit), offset]);
      const [countRows] = await db.execute(countSql, [userId]);
      
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / limit);
      
      res.json({
        success: true,
        message: '获取积分历史成功',
        data: {
          history: historyRows,
          pagination: {
            current_page: parseInt(page),
            total_pages: totalPages,
            total_items: total,
            items_per_page: parseInt(limit)
          }
        }
      });
    } catch (error) {
      logger.error('获取积分历史失败:', error);
      res.status(500).json({
        success: false,
        message: '获取积分历史失败',
        error_code: 'GET_POINTS_HISTORY_ERROR'
      });
    }
  }

  /**
   * 获取用户订单历史
   * GET /api/users/:userId/orders
   */
  static async getUserOrders(req, res) {
    try {
      const { userId } = req.params;
      const { page = 1, limit = 10, status } = req.query;
      
      const offset = (page - 1) * limit;
      
      let whereClause = 'WHERE o.user_id = ?';
      let queryParams = [userId];
      
      if (status) {
        whereClause += ' AND o.status = ?';
        queryParams.push(status);
      }
      
      const sql = `
        SELECT 
          o.order_id,
          o.order_number,
          o.total_amount,
          o.status,
          o.order_type,
          o.created_at,
          o.updated_at,
          COUNT(oi.order_item_id) as item_count
        FROM orders o
        LEFT JOIN order_items oi ON o.order_id = oi.order_id
        ${whereClause}
        GROUP BY o.order_id
        ORDER BY o.created_at DESC 
        LIMIT ? OFFSET ?
      `;
      
      const countSql = `SELECT COUNT(DISTINCT o.order_id) as total FROM orders o ${whereClause}`;
      
      queryParams.push(parseInt(limit), offset);
      
      const [orderRows] = await db.execute(sql, queryParams);
      const [countRows] = await db.execute(countSql, queryParams.slice(0, -2));
      
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / limit);
      
      res.json({
        success: true,
        message: '获取订单历史成功',
        data: {
          orders: orderRows,
          pagination: {
            current_page: parseInt(page),
            total_pages: totalPages,
            total_items: total,
            items_per_page: parseInt(limit)
          }
        }
      });
    } catch (error) {
      logger.error('获取用户订单失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单历史失败',
        error_code: 'GET_USER_ORDERS_ERROR'
      });
    }
  }

  /**
   * 获取用户优惠券
   * GET /api/users/:userId/coupons
   */
  static async getUserCoupons(req, res) {
    try {
      const { userId } = req.params;
      const { status = 'available' } = req.query;
      
      let whereClause = 'WHERE uc.user_id = ?';
      let queryParams = [userId];
      
      if (status === 'available') {
        whereClause += ' AND uc.is_used = false AND c.expires_at > NOW()';
      } else if (status === 'used') {
        whereClause += ' AND uc.is_used = true';
      } else if (status === 'expired') {
        whereClause += ' AND uc.is_used = false AND c.expires_at <= NOW()';
      }
      
      const sql = `
        SELECT 
          uc.user_coupon_id,
          uc.is_used,
          uc.used_at,
          uc.obtained_at,
          c.coupon_id,
          c.title,
          c.description,
          c.discount_type,
          c.discount_value,
          c.minimum_order_amount,
          c.expires_at,
          c.terms_conditions
        FROM user_coupons uc
        JOIN coupons c ON uc.coupon_id = c.coupon_id
        ${whereClause}
        ORDER BY 
          CASE WHEN uc.is_used = false AND c.expires_at > NOW() THEN 0 ELSE 1 END,
          c.expires_at ASC
      `;
      
      const [couponRows] = await db.execute(sql, queryParams);
      
      res.json({
        success: true,
        message: '获取用户优惠券成功',
        data: {
          coupons: couponRows
        }
      });
    } catch (error) {
      logger.error('获取用户优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户优惠券失败',
        error_code: 'GET_USER_COUPONS_ERROR'
      });
    }
  }

  /**
   * 获取用户统计信息
   * GET /api/users/:userId/stats
   */
  static async getUserStats(req, res) {
    try {
      const { userId } = req.params;
      
      // 获取用户基本信息
      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }
      
      // 获取订单统计
      const orderStatsSql = `
        SELECT 
          COUNT(*) as total_orders,
          COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_orders,
          COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_orders,
          COALESCE(SUM(CASE WHEN status = 'completed' THEN total_amount ELSE 0 END), 0) as total_spent
        FROM orders 
        WHERE user_id = ?
      `;
      
      // 获取优惠券统计
      const couponStatsSql = `
        SELECT 
          COUNT(*) as total_coupons,
          COUNT(CASE WHEN is_used = true THEN 1 END) as used_coupons,
          COUNT(CASE WHEN is_used = false AND c.expires_at > NOW() THEN 1 END) as available_coupons
        FROM user_coupons uc
        JOIN coupons c ON uc.coupon_id = c.coupon_id
        WHERE uc.user_id = ?
      `;
      
      // 获取最近订单
      const recentOrdersSql = `
        SELECT order_id, order_number, total_amount, status, created_at
        FROM orders 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 5
      `;
      
      const [orderStatsRows] = await db.execute(orderStatsSql, [userId]);
      const [couponStatsRows] = await db.execute(couponStatsSql, [userId]);
      const [recentOrdersRows] = await db.execute(recentOrdersSql, [userId]);
      
      const orderStats = orderStatsRows[0];
      const couponStats = couponStatsRows[0];
      
      res.json({
        success: true,
        message: '获取用户统计信息成功',
        data: {
          user_info: {
            membership_level: user.membership_level,
            points_balance: user.points_balance,
            total_spent: parseFloat(user.total_spent),
            member_since: user.created_at
          },
          order_stats: {
            total_orders: parseInt(orderStats.total_orders),
            completed_orders: parseInt(orderStats.completed_orders),
            cancelled_orders: parseInt(orderStats.cancelled_orders),
            total_spent: parseFloat(orderStats.total_spent)
          },
          coupon_stats: {
            total_coupons: parseInt(couponStats.total_coupons || 0),
            used_coupons: parseInt(couponStats.used_coupons || 0),
            available_coupons: parseInt(couponStats.available_coupons || 0)
          },
          recent_orders: recentOrdersRows
        }
      });
    } catch (error) {
      logger.error('获取用户统计信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户统计信息失败',
        error_code: 'GET_USER_STATS_ERROR'
      });
    }
  }

  /**
   * 删除用户账户（软删除）
   * DELETE /api/users/:userId
   */
  static async deleteUser(req, res) {
    try {
      const { userId } = req.params;
      
      const user = await User.findById(userId);
      if (!user) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      // 执行软删除
      await user.softDelete();
      
      res.json({
        success: true,
        message: '用户账户已删除'
      });
    } catch (error) {
      logger.error('删除用户失败:', error);
      res.status(500).json({
        success: false,
        message: '删除用户失败',
        error_code: 'DELETE_USER_ERROR'
      });
    }
  }

  /**
   * 搜索用户（管理员功能）
   * GET /api/users/search
   */
  static async searchUsers(req, res) {
    try {
      const { keyword, page = 1, limit = 20, sort = 'created_at', order = 'desc' } = req.query;
      
      const offset = (page - 1) * limit;
      
      let whereClause = 'WHERE is_active = true';
      let queryParams = [];
      
      if (keyword) {
        whereClause += ' AND (username LIKE ? OR email LIKE ? OR first_name LIKE ? OR last_name LIKE ?)';
        const searchTerm = `%${keyword}%`;
        queryParams.push(searchTerm, searchTerm, searchTerm, searchTerm);
      }
      
      const validSortFields = ['created_at', 'updated_at', 'username', 'email', 'total_spent', 'points_balance'];
      const sortField = validSortFields.includes(sort) ? sort : 'created_at';
      const sortOrder = order.toLowerCase() === 'asc' ? 'ASC' : 'DESC';
      
      const sql = `
        SELECT 
          user_id, username, email, first_name, last_name,
          membership_level, points_balance, total_spent,
          email_verified, phone_verified, last_login_at, created_at
        FROM users 
        ${whereClause}
        ORDER BY ${sortField} ${sortOrder}
        LIMIT ? OFFSET ?
      `;
      
      const countSql = `SELECT COUNT(*) as total FROM users ${whereClause}`;
      
      queryParams.push(parseInt(limit), offset);
      
      const [userRows] = await db.execute(sql, queryParams);
      const [countRows] = await db.execute(countSql, queryParams.slice(0, -2));
      
      const total = countRows[0].total;
      const totalPages = Math.ceil(total / limit);
      
      res.json({
        success: true,
        message: '搜索用户成功',
        data: {
          users: userRows,
          pagination: {
            current_page: parseInt(page),
            total_pages: totalPages,
            total_items: total,
            items_per_page: parseInt(limit)
          }
        }
      });
    } catch (error) {
      logger.error('搜索用户失败:', error);
      res.status(500).json({
        success: false,
        message: '搜索用户失败',
        error_code: 'SEARCH_USERS_ERROR'
      });
    }
  }

  /**
   * 获取所有用户（管理员功能）
   * GET /api/admin/users
   */
  static async getAllUsers(req, res) {
    try {
      const { page = 1, limit = 10, search = '', status = '' } = req.query;
      const offset = (page - 1) * limit;

      let whereClause = '';
      const params = [];

      if (search) {
        whereClause += ' WHERE (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
        params.push(`%${search}%`, `%${search}%`, `%${search}%`);
      }

      if (status) {
        whereClause += search ? ' AND' : ' WHERE';
        whereClause += ' is_active = ?';
        params.push(status === 'active' ? 1 : 0);
      }

      const countQuery = `SELECT COUNT(*) as total FROM users${whereClause}`;
      const [countResult] = await db.execute(countQuery, params);
      const total = countResult[0].total;

      const query = `
        SELECT user_id, username, email, phone, first_name, last_name, 
               date_of_birth, gender, membership_level, points_balance, 
               is_active, email_verified, phone_verified, created_at, 
               updated_at, last_login_at
        FROM users
        ${whereClause}
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;
      params.push(parseInt(limit), offset);

      const [users] = await db.execute(query, params);

      res.json({
        success: true,
        message: '获取用户列表成功',
        data: {
          users,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error) {
      logger.error('获取用户列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户列表失败',
        error_code: 'GET_USERS_ERROR'
      });
    }
  }

  /**
   * 更新用户状态（管理员功能）
   * PUT /api/admin/users/:id/status
   */
  static async updateUserStatus(req, res) {
    try {
      const { id } = req.params;
      const { is_active } = req.body;

      const query = 'UPDATE users SET is_active = ?, updated_at = NOW() WHERE id = ?';
      const [result] = await db.execute(query, [is_active, id]);

      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      res.json({
        success: true,
        message: '用户状态更新成功'
      });
    } catch (error) {
      logger.error('更新用户状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新用户状态失败',
        error_code: 'UPDATE_USER_STATUS_ERROR'
      });
    }
  }

  /**
   * 重置用户密码（管理员功能）
   * POST /api/admin/users/:id/reset-password
   */
  static async resetUserPassword(req, res) {
    try {
      const { id } = req.params;
      const bcrypt = require('bcryptjs');
      
      // 生成默认密码
      const defaultPassword = '123456';
      const hashedPassword = await bcrypt.hash(defaultPassword, 10);

      const query = 'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?';
      const [result] = await db.execute(query, [hashedPassword, id]);

      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在',
          error_code: 'USER_NOT_FOUND'
        });
      }

      res.json({
        success: true,
        message: '密码重置成功，新密码为：123456'
      });
    } catch (error) {
      logger.error('重置用户密码失败:', error);
      res.status(500).json({
        success: false,
        message: '重置用户密码失败',
        error_code: 'RESET_PASSWORD_ERROR'
      });
    }
  }

  /**
   * 获取用户统计信息（管理员功能）
   * GET /api/admin/users/statistics
   */
  static async getUserStatistics(req, res) {
    try {
      const queries = {
        total: 'SELECT COUNT(*) as count FROM users',
        active: 'SELECT COUNT(*) as count FROM users WHERE is_active = 1',
        inactive: 'SELECT COUNT(*) as count FROM users WHERE is_active = 0',
        newThisMonth: `
          SELECT COUNT(*) as count FROM users 
          WHERE DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
        `,
        newToday: `
          SELECT COUNT(*) as count FROM users 
          WHERE DATE(created_at) = CURDATE()
        `
      };

      const results = {};
      for (const [key, query] of Object.entries(queries)) {
        const [result] = await db.execute(query);
        results[key] = result[0].count;
      }

      // 会员等级维度统计
      const [levelCounts] = await db.execute(`
        SELECT membership_level, COUNT(*) AS count 
        FROM users 
        GROUP BY membership_level
      `);

      const [levelNewThisMonth] = await db.execute(`
        SELECT membership_level, COUNT(*) AS count 
        FROM users 
        WHERE DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
        GROUP BY membership_level
      `);

      const [levelNewToday] = await db.execute(`
        SELECT membership_level, COUNT(*) AS count 
        FROM users 
        WHERE DATE(created_at) = CURDATE()
        GROUP BY membership_level
      `);

      const [levelSpend] = await db.execute(`
        SELECT membership_level, COALESCE(SUM(total_spent), 0) AS total_spent
        FROM users
        GROUP BY membership_level
      `);

      // 转换为键值对便于前端渲染
      const toMap = (rows, key, valueKey) => {
        const map = {};
        for (const r of rows) {
          map[r[key] || 'unknown'] = Number(r[valueKey] || 0);
        }
        return map;
      };

      const membership = {
        counts: toMap(levelCounts, 'membership_level', 'count'),
        new_this_month: toMap(levelNewThisMonth, 'membership_level', 'count'),
        new_today: toMap(levelNewToday, 'membership_level', 'count'),
        spend: toMap(levelSpend, 'membership_level', 'total_spent')
      };

      res.json({
        success: true,
        message: '获取用户统计信息成功',
        data: {
          ...results,
          membership
        }
      });
    } catch (error) {
      logger.error('获取用户统计信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户统计信息失败',
        error_code: 'GET_USER_STATISTICS_ERROR'
      });
    }
  }
  /**
   * 获取用户会员状态（等级、积分余额、进度、即将到期）
   * GET /api/users/:userId/loyalty-status
   */
  static async getLoyaltyStatus(req, res) {
    try {
      const { userId } = req.params;
      // 当前积分余额与基本信息
      const userRows = await db.execute(
        `SELECT user_id, membership_level, points_balance FROM users WHERE user_id = ?`,
        [userId]
      );
      const user = Array.isArray(userRows[0]) ? userRows[0][0] : userRows[0];
      if (!user) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
  
      // 计算累计获得积分与等级
      const [lifetimeRows] = await db.execute(
        `SELECT COALESCE(SUM(points_change), 0) AS lifetime
         FROM points_history
         WHERE user_id = ? AND type = 'earn' AND status IN ('active','expired')`,
        [userId]
      );
      const lifetime = lifetimeRows[0]?.lifetime || 0;
  
      // 阈值与下一等级进度
      const thresholds = [200, 800, 1600];
      let currentLevel = 'bronze';
      if (lifetime >= 1600) currentLevel = 'platinum';
      else if (lifetime >= 800) currentLevel = 'gold';
      else if (lifetime >= 200) currentLevel = 'silver';
  
      const nextThreshold = lifetime >= 1600 ? null : (lifetime >= 800 ? 1600 : (lifetime >= 200 ? 800 : 200));
      const progressToNext = nextThreshold ? Math.max(0, nextThreshold - lifetime) : 0;
  
      // 30天内即将过期的积分（earn未过期）
      const [expRows] = await db.execute(
        `SELECT COALESCE(SUM(points_change), 0) AS expiring
         FROM points_history
         WHERE user_id = ? AND type = 'earn' AND status = 'active' AND expires_at IS NOT NULL AND expires_at <= DATE_ADD(NOW(), INTERVAL 30 DAY)`,
        [userId]
      );
      const expiringSoon = expRows[0]?.expiring || 0;
  
      return res.json({
        success: true,
        message: '获取会员状态成功',
        data: {
          user_id: Number(userId),
          membership_level: currentLevel,
          points_balance: user.points_balance,
          lifetime_points: lifetime,
          next_level_threshold: nextThreshold,
          points_to_next_level: progressToNext,
          expiring_soon_points_30d: expiringSoon
        }
      });
    } catch (error) {
      logger.error('获取会员状态失败:', error);
      res.status(500).json({ success: false, message: '获取会员状态失败', error_code: 'GET_LOYALTY_STATUS_ERROR' });
    }
  }
}

module.exports = UserController;